import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal, Form, Input, Checkbox, Progress, Button, message } from 'antd';
import { useEffect, useState } from 'react';

import { applyContract } from '@/services/orderManage';
import { getErrorMsg } from '@/util/utils';

import styles from './index.less';

interface Props {
  isContractVisible: boolean;
  setIsContractVisible: (b: boolean) => void;
  title: string;
  selectKeys?: string[];
  handleOkAfter?: () => void;
}

export enum ContractTypeEnum {
  Apply = '申请合同',
  View = '查看合同',
  DownLoad = '下载合同',
}

export default function ContractModal(props: Props) {
  const { isContractVisible, setIsContractVisible, title, selectKeys, handleOkAfter } = props;
  const [okButtonDisabled, setOkButtonDisabled] = useState<boolean>(true);
  const [downLoadModal, setDownLoadModal] = useState<boolean>(false);
  const [okText, setOkText] = useState<string>('提交');
  const [form] = Form.useForm();
  const handleOk = () => {
    const formData = form.getFieldsValue();
    if (title === ContractTypeEnum.Apply) {
      form.validateFields().then(async () => {
        const payload = {
          ...formData,
          saasOrderIds: selectKeys,
        };
       const res = await applyContract(payload);
       if (res.code===200) {
         setIsContractVisible(false);
         message.success('申请合同成功!');
         if (handleOkAfter) {
           handleOkAfter();
         }
       } else {
         message.error(getErrorMsg(res));
       }
      });
      setOkButtonDisabled(true);
    } else {
      setIsContractVisible(true);
      setDownLoadModal(true);
      console.log('下载合同按钮>>>>>>>>>>');
    }
  };

  useEffect(() => {
    if (title === ContractTypeEnum.View) {
      setOkText(ContractTypeEnum.DownLoad);
      setOkButtonDisabled(false);
    }
  }, [title]);

  const switchDownLoad = () => {
    if (downLoadModal) {
      return (
        <div className={styles.downContract}>
          <div>
            <Progress type="dashboard" percent={75} gapDegree={0}/>
          </div>
          <div>合同生成中...</div>
          <div>您可以继续等待或稍后在订单中后点击查看合同下载</div>
        </div>
      );
    }
    return (
      <div className={styles.seeContract}>
        <div>申请人：{'颤三'}</div>
        <div>申请时间：{'2022年9月10日'}</div>
        <div>合同编号：{'JSSY_20220222_867891260031'}</div>
      </div>
    );
  };

  return (
    <Modal
      destroyOnClose
      title={title}
      visible={isContractVisible}
      okText={okText}
      onOk={handleOk}
      onCancel={() => {
        setIsContractVisible(false);
        if (title === ContractTypeEnum.Apply) {
          setOkButtonDisabled(true);
        } else {
          setDownLoadModal(false);
        }
      }}
      okButtonProps={{ disabled: okButtonDisabled }}
      footer={
        downLoadModal
          ? [
            <Button
              style={{ background: '#1A3DC9', color: '#fff' }}
              onClick={() => {
                setIsContractVisible(false);
                setDownLoadModal(false);
              }}
              key="ok"
            >
              好的
            </Button>,
          ]
          : [
            <Button
              key="cancel"
              onClick={() => {
                setIsContractVisible(false);
                if (title === ContractTypeEnum.Apply) {
                  setOkButtonDisabled(true);
                } else {
                  setDownLoadModal(false);
                }
              }}
            >
              取消
            </Button>,
            <Button
              style={!okButtonDisabled ? { background: '#1A3DC9', color: '#fff' } : {}}
              disabled={okButtonDisabled}
              key="submit"
              onClick={handleOk}
            >
              {okText}
            </Button>,
          ]
      }
    >
      {title === ContractTypeEnum.View ? (
        switchDownLoad()
      ) : (
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 19 }} autoComplete="off">
          <Form.Item label="企业全称" name="companyName" rules={[{ required: true, message: '请输入服务企业全称' }]}>
            <Input placeholder="请输入服务企业全称"/>
          </Form.Item>

          <Form.Item label="信用代码" name="uscCode" rules={[{ required: true, message: '请输入统一信用代码' }]}>
            <Input placeholder="请输入统一信用代码"/>
          </Form.Item>

          <Form.Item label="联系电话" name="contactPhone" rules={[{ required: true, message: '请输入可用的联系电话（座机：区号-座机号码 例如 025-58713607）', pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/ }]}>
            <Input placeholder="请输入可用的联系电话"/>
          </Form.Item>

          <Form.Item label="通讯地址" name="address" rules={[{ required: true, message: '请填写通讯地址' }]}>
            <Input placeholder="请填写通讯地址"/>
          </Form.Item>
          <Form.Item style={{ marginTop: 40 }}>
            <Checkbox onChange={(e) => setOkButtonDisabled(!e.target.checked)}>
              已确认信息填写无误
            </Checkbox>
            <div className={styles.contractModal}>
              <ExclamationCircleOutlined/>
              <span>合同仅可申请一次。为了避免不必要的麻烦，请仔细确认填写无误后再提交</span>
            </div>
          </Form.Item>
        </Form>
      )}
    </Modal>
  );
}
